//
//  EFNewDeliveryAddressViewController.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/7.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFNewDeliveryAddressViewController.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "EFAddressMarkViewPicker.h"
#import "EFUserLocationItem.h"
#import "iToast.h"
#import "EFSearchAddressViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@interface EFNewDeliveryAddressViewController ()<AddressDelegate,ABPeoplePickerNavigationControllerDelegate>

@property(strong,nonatomic)UILabel* locateTipsLabel;
@property(strong,nonatomic)UIImageView* locateIV;
@property(strong,nonatomic)UILabel* locateLabel;
@property(strong,nonatomic)UIImageView* locateMoreIV;
@property(strong,nonatomic)UIView* locateLineView;

@property(strong,nonatomic)UILabel* houseNumberLabel;
@property(strong,nonatomic) UITextField *houseNumberTextF;
@property(strong,nonatomic)UIView* houseNumberLineView;


@property(strong,nonatomic)UILabel* receiverLabel;
@property(strong,nonatomic) UITextField *receiverTextF;
@property(strong,nonatomic)UIView* receiverLineView;


@property(strong,nonatomic)UILabel* phoneLabel;
@property(strong,nonatomic) UITextField *phoneTextF;
@property(strong,nonatomic)UIView* phoneLineView;
@property(strong,nonatomic)UIImageView* phoneIV;


@property(strong,nonatomic)UILabel* markTipsLabel;
@property(strong,nonatomic)UILabel* markLabel;
@property(strong,nonatomic)UIImageView* markMoreIV;

@property(strong,nonatomic)EFAddressMarkViewPicker* addressPicker;


@property (strong, nonatomic) TPKeyboardAvoidingScrollView * scrollView;


@property(strong,nonatomic) UIButton *addBtn;

@property(strong,nonatomic) NSString* selectMark;
@property(strong,nonatomic) EFMyDeliveryAddressViewItem *item;
@property(assign,nonatomic) Boolean isFromLocation;

@property (strong, nonatomic)EFUserLocationItem *locationItem;
@property (strong, nonatomic)NSString *addressDetial;
@property (strong, nonatomic)NSString *address;
@property (strong, nonatomic)NSString *addressName;
@property (strong,nonatomic)ABPeoplePickerNavigationController* peoplePicker;

@end

@implementation EFNewDeliveryAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.item = nil;
        self.title = @"添加新地址";
        self.selectMark = @"";
    }
    return self;
}

-(instancetype)initWithItem:(EFMyDeliveryAddressViewItem *)item{
    self = [super init];
    if(self){
        self.locationItem = APP_CONTEXT.locationManager.pinLocation;
        self.locationItem.address = item.addressName;
        self.locationItem.detailAddress = item.addressDetail;
        
        [self.locateLabel setText:item.addressName];
        [self.houseNumberTextF setText:item.address];
        [self.receiverTextF setText:item.name];
        [self.phoneTextF setText:item.phone];
        [self.markLabel setText:item.tag];
        self.selectMark = item.tag;
        self.title = @"编辑收货地址";
        self.item = item;
    }
    
    return self;
}

-(instancetype)initWithLocation{
    self = [self init];
    if(self){
        EFUserLocationItem* location = APP_CONTEXT.locationManager.pinLocation;
        self.locationItem = location;
        [self.locateLabel setText:location.address];
//        [self.houseNumberTextF setText:location.detailAddress];
        self.isFromLocation = true;
    }
    
    return self;
}


-(void)initView{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.locateTipsLabel];
    [self.scrollView addSubview:self.locateIV];
    [self.scrollView addSubview:self.locateLabel];
    [self.scrollView addSubview:self.locateMoreIV];
    [self.scrollView addSubview:self.locateLineView];
    
    [self.scrollView addSubview:self.houseNumberLabel];
    [self.scrollView addSubview:self.houseNumberTextF];
    [self.scrollView addSubview:self.houseNumberLineView];
    
    
    [self.scrollView addSubview:self.receiverLabel];
    [self.scrollView addSubview:self.receiverTextF];
    [self.scrollView addSubview:self.receiverLineView];
    
    
    [self.scrollView addSubview:self.phoneLabel];
    [self.scrollView addSubview:self.phoneTextF];
    [self.scrollView addSubview:self.phoneLineView];
    [self.scrollView addSubview:self.phoneIV];
    
    [self.scrollView addSubview:self.markTipsLabel];
    [self.scrollView addSubview:self.markLabel];
    [self.scrollView addSubview:self.markMoreIV];
    
    [self.scrollView addSubview:self.addBtn];
    [self.view addSubview:self.scrollView];
}

-(void)showToastMessage:(NSString*) message{
    [[iToast makeText:message] show];
}

-(void)onClickAdd{
    NSString* receiver =  self.receiverTextF.text;
    if(receiver == nil || receiver.length <=0){
        [self showToastMessage:@"收货人不能为空"];
        return;
    }
    
    NSString* phone =  self.phoneTextF.text;
    if(phone == nil || phone.length <=0){
        [self showToastMessage:@"电话不能为空"];
        return;
    }
    NSString* address =   self.houseNumberTextF.text;
    if(address == nil || address.length <=0){
        [self showToastMessage:@"地址不能为空"];
        return;
    }
    
    
//    EFUserLocationItem* location = APP_CONTEXT.locationManager.pinLocation;
    NSString* addressName =   self.locateLabel.text;
    NSString* position =  [NSString stringWithFormat:@"%lf,%lf",self.locationItem.userCoordinate.longitude,self.locationItem.userCoordinate.latitude];
    
    NSString* addressDetail =   self.locationItem.detailAddress;
//    if(self.selectMark == nil || self.selectMark.length <=0){
//        [self showToastMessage:@"请选择标签"];
//        return;
//    }
    
    if(!addressName){
        addressName = @"";
    }
    if(!addressDetail){
        addressDetail = @"";
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:receiver forKey:@"name"];
    [dic setValue:phone forKey:@"phone"];
    [dic setValue:address forKey:@"address"];
    [dic setValue:addressName forKey:@"addressName"];
    [dic setValue:addressDetail forKey:@"addressDetail"];
    [dic setValue:position forKey:@"position"];
    [dic setValue:self.selectMark forKey:@"tag"];
 
    if(self.item){
        [dic setValue:self.item.id forKey:@"id"];
        
        __weak typeof(self) weakSelf = self;
        [APP_CONTEXT.net editAddressWithParams:dic
           OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
               if (code == 0) {
                   [weakSelf showToastMessage:@"修改成功"];
                   [weakSelf back:nil];
               }else{
                   [weakSelf showToastMessage:message];
               }
           }];
    }else{
        __weak typeof(self) weakSelf = self;
        [APP_CONTEXT.net addAddressWithParams:dic OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if (code == 0) {
                if(weakSelf.isFromLocation){
                    EFMyDeliveryAddressViewItem* item =[[EFMyDeliveryAddressViewItem alloc]init];
                    item.id = [info objectForKey:@"addrId"];
                    item.address = address;
                    item.addressDetail = addressDetail;
                    item.name = receiver;
                    item.phone = phone;
                    item.addressName = addressName;
                    item.tag = self.selectMark;
                    item.position = position;
                    [weakSelf setDefault:item];
                }
                [weakSelf showToastMessage:@"添加成功"];
                [weakSelf back:nil];
            }else{
                [weakSelf showToastMessage:message];
            }
        }];
 
    }
}

-(TPKeyboardAvoidingScrollView*)scrollView{
    if(_scrollView == NULL){
        _scrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame: CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _scrollView.contentSize =  CGSizeMake(kScreenWidth, kScreenHeight - kStatusBarHeight);
    }
    return _scrollView;
}


-(UILabel *)locateTipsLabel{
    if(_locateTipsLabel == NULL){
        _locateTipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 15)];
        _locateTipsLabel.left = 20;
        _locateTipsLabel.top = 19;
        _locateTipsLabel.font = [UIFont systemFontOfSize:13];
        _locateTipsLabel.textColor = kBlack333;
        _locateTipsLabel.text = @"收货地址";
        [_locateTipsLabel sizeToFit];
    }
    return _locateTipsLabel;
}

-(UIImageView*)locateIV{
    if(_locateIV == NULL){
        _locateIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
        _locateIV.left = self.locateTipsLabel.right + 15;
        _locateIV.top = 15;
        _locateIV.image = IMG(@"nav_icon_position_default");
    }
    return _locateIV;
}

-(UILabel *)locateLabel{
    if(_locateLabel == NULL){
        _locateLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 15)];
        _locateLabel.left = self.locateIV.right + 1;
        _locateLabel.top = 19;
        _locateLabel.font = [UIFont systemFontOfSize:13];
        _locateLabel.textColor = kBlack333;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(turnToAddressPage)];
        [_locateLabel addGestureRecognizer:tap];
        _locateLabel.userInteractionEnabled = YES;
    }
    return _locateLabel;
}

- (void)turnToAddressPage{
    EFSearchAddressViewController *VC = [[EFSearchAddressViewController alloc] init];
    VC.delegate = self;
    // [ICNavigator presentViewController:VC animated:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

-(UIImageView*)locateMoreIV{
    if(_locateMoreIV == NULL){
        _locateMoreIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
        _locateMoreIV.left = kScreenWidth -  _locateMoreIV.width -20 ;
        _locateMoreIV.top = 15;
        _locateMoreIV.image = IMG(@"more_icon_me_default");
    }
    return _locateMoreIV;
}

-(UIView *)locateLineView{
    if(_locateLineView == NULL){
        _locateLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 1)];
        _locateLineView.left = 20;
        _locateLineView.top = self.locateTipsLabel.bottom + 11;
        _locateLineView.backgroundColor = RGBCOLOR(0xECECEC);
    }
    return _locateLineView;
}

-(UILabel *)houseNumberLabel{
    if(_houseNumberLabel == NULL){
        _houseNumberLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 15)];
        _houseNumberLabel.left = 20;
        _houseNumberLabel.top = self.locateLineView.bottom + 13;
        _houseNumberLabel.font = [UIFont systemFontOfSize:13];
        _houseNumberLabel.textColor = kBlack333;
        _houseNumberLabel.text = @"门牌号";
        [_houseNumberLabel sizeToFit];
    }
    return _houseNumberLabel;
}

-(UITextField *)houseNumberTextF{
    if(_houseNumberTextF == NULL){
        _houseNumberTextF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 100, 15)];
        _houseNumberTextF.left = self.houseNumberLabel.right + 28;;
        _houseNumberTextF.top = self.locateLineView.bottom + 13;
        _houseNumberTextF.font = [UIFont systemFontOfSize:13];
        _houseNumberTextF.textColor = kBlack999;
        _houseNumberTextF.keyboardType = UIKeyboardTypeDefault;
//        _houseNumberTextF.delegate = self;
        _houseNumberTextF.placeholder = @"详细地址：例如1单元101室";
    }
    
    return _houseNumberTextF;
}


-(UIView *)houseNumberLineView{
    if(_houseNumberLineView == NULL){
        _houseNumberLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 1)];
        _houseNumberLineView.left = 20;
        _houseNumberLineView.top = self.houseNumberLabel.bottom + 11;
        _houseNumberLineView.backgroundColor = RGBCOLOR(0xECECEC);
    }
    return _houseNumberLineView;
}


-(UILabel *)receiverLabel{
    if(_receiverLabel == NULL){
        _receiverLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 15)];
        _receiverLabel.left = 20;
        _receiverLabel.top = self.houseNumberLineView.bottom + 13;
        _receiverLabel.font = [UIFont systemFontOfSize:13];
        _receiverLabel.textColor = kBlack333;
        _receiverLabel.text = @"收货人";
        [_receiverLabel sizeToFit];
    }
    return _receiverLabel;
}

-(UITextField *)receiverTextF{
    if(_receiverTextF == NULL){
        _receiverTextF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 100, 15)];
        _receiverTextF.left = self.receiverLabel.right + 28;;
        _receiverTextF.top = self.houseNumberLineView.bottom + 13;
        _receiverTextF.font = [UIFont systemFontOfSize:13];
        _receiverTextF.textColor = kBlack999;
        _receiverTextF.keyboardType = UIKeyboardTypeDefault;
        //        _houseNumberTextF.delegate = self;
        _receiverTextF.placeholder = @"填写收货人姓名";
    }
    
    return _receiverTextF;
}


-(UIView *)receiverLineView{
    if(_receiverLineView == NULL){
        _receiverLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 1)];
        _receiverLineView.left = 20;
        _receiverLineView.top = self.receiverLabel.bottom + 11;
        _receiverLineView.backgroundColor = RGBCOLOR(0xECECEC);
    }
    return _receiverLineView;
}


-(UILabel *)phoneLabel{
    if(_phoneLabel == NULL){
        _phoneLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 15)];
        _phoneLabel.left = 20;
        _phoneLabel.top = self.receiverLineView.bottom + 13;
        _phoneLabel.font = [UIFont systemFontOfSize:13];
        _phoneLabel.textColor = kBlack333;
        _phoneLabel.text = @"手机号";
        [_phoneLabel sizeToFit];
    }
    return _phoneLabel;
}

-(UITextField *)phoneTextF{
    if(_phoneTextF == NULL){
        _phoneTextF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 100, 15)];
        _phoneTextF.left = self.phoneLabel.right + 28;;
        _phoneTextF.top = self.receiverLineView.bottom + 13;
        _phoneTextF.font = [UIFont systemFontOfSize:13];
        _phoneTextF.textColor = kBlack999;
        _phoneTextF.keyboardType = UIKeyboardTypeDefault;
        //        _houseNumberTextF.delegate = self;
        _phoneTextF.placeholder = @"填写手机号";
    }
    
    return _phoneTextF;
}


-(UIImageView *)phoneIV{
    if(_phoneIV == NULL){
        _phoneIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
        _phoneIV.left = kScreenWidth -  _phoneIV.width - 18 ;
        _phoneIV.top = self.receiverLineView.bottom + 7;
        _phoneIV.image = IMG(@"address_phonebook_icon");
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickPhone)];
        [_phoneIV addGestureRecognizer:tap];
        _phoneIV.userInteractionEnabled = YES;
    }
    return _phoneIV;
}

-(UIView *)phoneLineView{
    if(_phoneLineView == NULL){
        _phoneLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 1)];
        _phoneLineView.left = 20;
        _phoneLineView.top = self.phoneLabel.bottom + 11;
        _phoneLineView.backgroundColor = RGBCOLOR(0xECECEC);
    }
    return _phoneLineView;
}


-(UILabel *)markTipsLabel{
    if(_markTipsLabel == NULL){
        _markTipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 15)];
        _markTipsLabel.left = 20;
        _markTipsLabel.top = self.phoneLineView.bottom + 13;
        _markTipsLabel.font = [UIFont systemFontOfSize:13];
        _markTipsLabel.textColor = kBlack333;
        _markTipsLabel.text = @"标签";
        [_markTipsLabel sizeToFit];
    }
    return _markTipsLabel;
}


-(UILabel *)markLabel{
    if(_markLabel == NULL){
        _markLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 15)];
        _markLabel.left = self.markTipsLabel.right + 41;
        _markLabel.top = self.phoneLineView.bottom + 13;
        _markLabel.font = [UIFont systemFontOfSize:13];
        _markLabel.textColor = kBlack999;
        _markLabel.text = @"选择“家”、“公司”";
        [_markLabel sizeToFit];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPositionPicker)];
        [_markLabel addGestureRecognizer:tap];
        _markLabel.userInteractionEnabled = YES;
    }
    return _markLabel;
}

-(UIImageView*)markMoreIV{
    if(_markMoreIV == NULL){
        _markMoreIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
        _markMoreIV.left = kScreenWidth -  _markMoreIV.width -20 ;
        _markMoreIV.top = self.phoneLineView.bottom + 15;
        _markMoreIV.image = IMG(@"more_icon_me_default");
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPositionPicker)];
        [_markMoreIV addGestureRecognizer:tap];
        _markMoreIV.userInteractionEnabled = YES;
    }
    return _markMoreIV;
}


-(UIButton *)addBtn{
    if(_addBtn == NULL){
        _addBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        _addBtn.top = kScreenHeight - kStatusBarHeight -  50;
        _addBtn.backgroundColor = RGBCOLOR(0x69BA45);
        _addBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _addBtn.titleLabel.textColor = [UIColor whiteColor];
        [_addBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(onClickAdd) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}


- (void)showPositionPicker{
    __weak __typeof(&*self)weakSelf = self;
    
    self.addressPicker = [[EFAddressMarkViewPicker alloc] init];
    [self.addressPicker show:self.selectMark];
    self.addressPicker.SuccessBlock = ^(NSString *title){
        weakSelf.selectMark = title;
        weakSelf.markLabel.text = title;
    };
}

-(void)setDefault:(EFMyDeliveryAddressViewItem*)item{
    [APP_CONTEXT.net setDefaultAddress:item.id OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if(code == 0){
            APP_CONTEXT.addressManager.defaultAddress = item;
            [APP_CONTEXT.addressManager persistenceAddressManager];
        }
    }];
}


- (void)addressSelected:(EFUserLocationItem *)info{
    self.locationItem = info;
    _locateLabel.text = [NSString stringWithFormat:@"%@",info.address];
}

-(void)onClickPhone{
    if (!self.peoplePicker) {
        self.peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
    }
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        self.peoplePicker.navigationBar.barTintColor = [UIColor whiteColor];
        self.peoplePicker.navigationBar.translucent = NO;
    } else {
        self.peoplePicker.navigationBar.tintColor = [UIColor whiteColor];
    }
    [self.peoplePicker.navigationBar setTitleTextAttributes:@{NSFontAttributeName: BFONT(20),
                                                              NSForegroundColorAttributeName: RGBCOLOR(0x333333)}];
    self.peoplePicker.peoplePickerDelegate = self;
    [self.navigationController presentViewController:self.peoplePicker animated:YES completion:nil];
}


#pragma mark - ABPeopleViewController Delegate

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    return YES;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    if (property == kABPersonPhoneProperty) {
        ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, property);
        int index = (int)ABMultiValueGetIndexForIdentifier(phoneMulti, identifier);
        NSString *phone = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneMulti, index);
        [self.phoneTextF setText:phone];
        CFRelease(phoneMulti);
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    }
    return NO;
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    [self peoplePickerNavigationController:peoplePicker shouldContinueAfterSelectingPerson:person property:property identifier:identifier];
    
}

@end
